﻿var cssRules = new Array();
var ___cssMenu = null;
var ___doClose=true;
var ___markDiv = null;
var ___markInnerDiv = null;
var ___currentMarkedObject = null;
var ___clickable = null;
var ___infoWindow = null;
var ___statusWindow = null;
var _lastchanges = null;

var appliedcss = new Array();
function showProcessDialog(txt)
{
    if ((!txt)||(txt==''))
    {
        if (___statusWindow == null)
            return;
        
        ___statusWindow.style.display = 'none';
    } else {
        if (___statusWindow == null)
        {
            ___statusWindow = document.createElement('div');
            ___statusWindow.style.border='solid 1px black';
            ___statusWindow.style.position='absolute';
            ___statusWindow.style.top = '200px';
            ___statusWindow.style.left = '400px';
            ___statusWindow.style.width = '200px';
            ___statusWindow.style.height = '40px';
            ___statusWindow.style.padding = '10px 10px 10px 10px';
            
            ___statusWindow.style.backgroundColor='white';            
            document.body.appendChild(___statusWindow);            
        }
        ___statusWindow.style.display='block';
        ___statusWindow.innerHTML = '<center>'+txt+'</center>';
    }
}
function Nada()
{
}
function whatdiv()
{
    dm(___currentMarkedObject.tagName + "#" + ___currentMarkedObject.id);
}
var cssed = null;
function showcss()
{   
	var docSSS = document.styleSheets;
	var htmlbody = document.getElementsByTagName('body')[0];
	if (cssRules.length>0)
	{
	    showProcessDialog('Stop css editor');
		deactivenode(htmlbody);
		cssRules = new Array();		
		if (___infoWindow)
		{
		    document.body.removeChild(___infoWindow);
		    ___infoWindow = null;
		}
		
		showProcessDialog('');
		return;
	}
    showProcessDialog('Start css editor');
	cssRules = new Array();
	for ( var i = 0; i< docSSS.length; i++) {
	    if (!docSSS[i].href)
	        continue;
	    if (docSSS[i].href.indexOf('contextmenu.css')>=0)
	        continue;
	    if (docSSS[i].href.indexOf('/themes/ui.') >= 0)
	        continue;
	    var media = docSSS[i].media;

	    if (media.mediaText)
	        media = media.mediaText;
	    if ((media) && (media != 'screen'))
	        continue;
	    var rules = docSSS[i].rules;
	    if (!rules)
	        rules = docSSS[i].cssRules;
		for (var j=0; j<rules.length;j++)
		{		   
			var txt = rules[j].selectorText;
			var id = '';
			var tag = '';
			var classname='';
			if (txt.match(/^#/ig))
			{
				id = txt.replace(/^#/ig,"");				
			} else {
				if (txt.indexOf('.')>0)
				{	
					tag = txt.substr(0,txt.indexOf('.'));
					classname=txt.substr(txt.indexOf('.')+1);
				} else {
					if (txt.indexOf('.')==0)
					{
						classname=txt.substr(1);
					} else {
						tag = txt;
					}
				}
            }
			if (tag.indexOf('ui-')<0)
			    cssRules[cssRules.length]=new CRule(tag,classname,id);				
		}
	}

	
	for (var k = 0; k<cssRules.length;k++)
	{
		activateNode(htmlbody,cssRules[k]);
	}

	showProcessDialog('');
	if (cssed == null) {
	    var obj = $('<div></div>').attr('id', 'ss');
	    obj.appendTo(document);
	    cssed = $(obj).cssDialog();
	}
}

function savecss()
{
    if (appliedcss.length>0)
	{
		var s = '';
		for ( var i = 0; i<appliedcss.length;i++)
		{
			s +=appliedcss[i].name+'@' + appliedcss[i].value+'$';
		}
		// save it
		showProcessDialog('Save css for this page...');
		var url = "cssEditor/Ajax/StyleManager.aspx";
		var params = "pageid="+_currentPageId+"&css="+encodeURIComponent(s);
		PostCss(url,params);
	} else {
	    alert('Nothing to save');
	}
}
function removecss()
{
	showProcessDialog('Moving css for this page...');
	var url = "cssEditor/Ajax/StyleManager.aspx";
	var params = "pageid="+_currentPageId+"&removemodifications=true";
	PostCss(url,params);
}
function savecssdone()
{
    showProcessDialog('Completed!<br/><input type=\"button\" onclick=\"showProcessDialog()\" value=\"OK\"></input>');    
}

function undocss()
{
	if (appliedcss.length>0)
	{
		var ss = document.styleSheets[document.styleSheets.length-1];
		var l = ss.rules.length;
		
		if (l>0)
		{
			ss.removeRule(l-1);
			_lastchanges = appliedcss[appliedcss.length-1];
			appliedcss.pop();
		}
		else
			alert('Nothing to undo');
				
	} else {
		alert('Nothing to undo');
	}
}


function deactivenode(node)
{
	if (node.nodeType == 3) 
	{
	} else {
		if (node.getAttribute('proced',0))
		{
			node.detachEvent('onmouseover',Hilite);
			node.detachEvent('onmouseout',Restore);			
            node.detachEvent('onclick',showMenu);    
            node.detachEvent('onmousedown',showMenu);  	
            if (node.tagName == 'A')
            {		
                node.removeAttribute('onmousedown',0);
            }
			node.removeAttribute('proced',0);
		}
		var kids = node.childNodes;
		for ( var i=0;i<kids.length;i++)
		{
			deactivenode(kids[i]);
		}		
	}
}
function activateNode(node,cl)
{
	if (node.nodeType == 3)
	    return;
	if (node.getAttribute('proced',0))
		return;

    var currentObj = $(node);
    //var className = $(node).attr('className');
    //if ((className) && (className.indexOf('ContextMenu') < 0))
    //    alert(className);
    if (currentObj.attr('id') == 'ss') {        
        return;
    }
    
	if ( (cl.IsMatchID(node)) ||  (cl.IsMatchTagClass(node)) ||  (cl.IsMatchClass(node))   ) {
	    currentObj.hover(Hilite,Restore);
		/*
		node.attachEvent('onmouseover',Hilite);
		node.attachEvent('onmouseout',Restore);
		node.setAttribute('proced','true',0);			
		*/
	} else {							
	    /*
	    if (window.detachEvent)
	    {
		    node.detachEvent('onmouseover',Hilite);
		    node.detachEvent('onmouseout',Restore);
            node.detachEvent('onclick',showMenu);    
            node.detachEvent('onmousedown',showMenu);  					    
		}		
		*/
	}
	var kids = node.childNodes;
	for ( var i=0;i<kids.length;i++) {
		activateNode(kids[i],cl);
	}

}
function showMenu()
{
    // not in edit mode;
    if (cssRules.length==0)
        return;
    var el = ___currentMarkedObject;
    if (el)
    {

        if (___infoWindow == null )
        {
            ___infoWindow = createInfoWindow();
        }
        if ( (___infoWindow==event.srcElement) || (contains(___infoWindow,event.srcElement)))
            return;
        
        if ( (event.srcElement==document.body) && (el!=document.body) )
            return;
        
                   
        clearInfoRows();
        
        updateInfoWindowPosition();
		var matchedclass = new Array();
		for (var i = 0 ;i < cssRules.length;i++)
		{
			if ( (cssRules[i].IsMatchID(el)) ||  (cssRules[i].IsMatchTagClass(el)) || (cssRules[i].IsMatchClass(el)) )
			{
				matchedclass[matchedclass.length]=cssRules[i];
			}
		}
		var ret = ''
		for ( var j =0 ;j<matchedclass.length;j++)
		{
			ret+="<div ><a href='javascript:void(0)' style='cursor:hand;' onclick=\"return editrule(\'"+matchedclass[j].ToString()+"\')\">";
			ret+='Change style : '+matchedclass[j].ToString();
			ret+="</a></div>";
		}				
        
        var elid = el.id==''?'':'#'+el.id;
        appendInfoRow("<div ><b>Current item:" + el.tagName + elid + "</b></div>");
        //appendInfoRow("<div class='ContextMenuItem'><i>Click on name to change the style for it</i></div>");
        appendInfoRow(ret);

    }
    return false;
}

function updateInfoWindowPosition()
{
    ___infoWindow.style.left = 0;//event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) ;
    ___infoWindow.style.top = (document.documentElement.scrollTop ? document.documentElement.scrollTop :  document.body.scrollTop);//event.clientY  + (document.documentElement.scrollTop ? document.documentElement.scrollTop :  document.body.scrollTop) ;

}
function showInfoWin(show)
{
    if (!___infoWindow)
        return;
        
    if (show)
    {
        ___infoWindow.style.display = 'block';
    } else {
        ___infoWindow.style.display = 'none';
    }
}
function addRulesToCss(rulename,s)
{
    var ss = document.styleSheets[document.styleSheets.length-1];

    var i =ss.addRule(rulename,s);
    appliedcss[appliedcss.length]=new myrule(rulename,s);
    _lastchanges = new myrule(rulename,s);            
}

var _currentTag = '';
function editrule(rulename) {
    cssed.dialog('open');
    cssed.find('.csstab2').tabs('select', 0);
    cssed.find('.descriptiondiv').text('');
    cssed.find('.previewContent').css({});
    cssed.find('.incsseditor').val('');    
    _currentTag = rulename;
    return false;   
}

function contains(a, b) 
{
  // Return true if node a contains node b.
  while (b.parentNode)
    if ((b = b.parentNode) == a)
      return true;
  return false;
}

function Hilite()
{	    
	if (!event.srcElement.runtimeStyle)
	    return;
	    
	var el = event.srcElement;
	if (___clickable==el)
	    return;
	    
    if ((el) && (el.id=='_md' || el.id=='_mid' || el.id=='styleInfoWindows' || ( contains(___infoWindow,el) ) ) )		    
        return;


	if (el == ___currentMarkedObject)
	    return;
	    
    window.event.cancelBubble = false;	
    window.event.returnValue = true;	

	var matchedclass = new Array();
	for (var i = 0 ;i < cssRules.length;i++)
	{
		if (cssRules[i].IsMatchID(el))
		{
			matchedclass[matchedclass.length]=cssRules[i];
		} else {
		    if (cssRules[i].IsMatchTagClass(el))
		    {
			    matchedclass[matchedclass.length]=cssRules[i];
		    } else {
		        if (cssRules[i].IsMatchClass(el))
		        {
			        matchedclass[matchedclass.length]=cssRules[i];
		        }
    		}
		}	
	}
	if (matchedclass.length>0)
	{
	    ___currentMarkedObject = el;
		var oldbgcolor = document.createAttribute("oldbgcolor");
		var oldborder = document.createAttribute("oldborder");
		
		oldbgcolor.value = el.runtimeStyle.backgroundColor;
		oldborder.value = el.runtimeStyle.border;
		
		el.attributes.setNamedItem(oldbgcolor);
		el.attributes.setNamedItem(oldborder);
		
		el.runtimeStyle.cursor = "crosshair";
		if (el.tagName == 'A')
		{
		    el.runtimeStyle.border = "solid 1px black";
		} else {
		    if (___markDiv == null)
		    {
		        ___markDiv = createMarkDiv('_md','white');
		        ___markInnerDiv = createMarkDiv('_mid','black');       
		    }
			
		    var ctop = cleft = 0;
		    var objWork = el;
		    if (objWork.offsetParent) 
		    {
		        do 
		        {    			
		            ctop += objWork.offsetTop;
		            cleft += objWork.offsetLeft;    			       			    
		        } while (objWork = objWork.offsetParent);
		    }
		    ___markDiv.style.top = ctop-2;
		    ___markDiv.style.left = cleft-2;
		    ___markDiv.style.height = el.offsetHeight+4;
		    ___markDiv.style.width = el.offsetWidth+4;
		    
		    ___markInnerDiv.style.top = ctop-1;
		    ___markInnerDiv.style.left = cleft-1;
		    ___markInnerDiv.style.height = el.offsetHeight+2;
		    ___markInnerDiv.style.width = el.offsetWidth+2;
		    
		}		
		Modify();
    }
}
function createInfoWindow()
{
    var obj = document.createElement('div');
    obj.style.position = 'absolute';

    obj.className = 'ContextMenu';
    obj.style.display = 'block';
    obj.id = 'styleInfoWindows';
    obj.style.top = '0px';
    obj.style.left = '0px';
    
    
    document.body.appendChild(obj);
    new dragObject("styleInfoWindows", null, new Position(0,0),null, null, null, null, false);
    
    return obj;
}
function clearInfoRows()
{
    if (___infoWindow==null)
        return;
    
    ___infoWindow.innerHTML='';
}
function appendInfoRow(msg)
{
    if (___infoWindow==null)
    {
        ___infoWindow = createInfoWindow();
    }
    
    ___infoWindow.innerHTML+=msg;
}
function createMarkDiv(idname,colorstring)
{
    var obj = document.createElement('div');
    obj.id = idname;
	obj.style.position='absolute';
    obj.style.display='block';
	obj.style.cursor = 'crosshair';
    //___markDiv.style.backgroundColor = 'white';
			    
	obj.runtimeStyle.border = "solid 1px " + colorstring;  			     
    obj.style.zIndex=10000;
    obj.style.filter = "alpha(opacity=50)";
		        
    document.body.appendChild(obj);
    return obj;
}
function Restore()
{    
	if (event.srcElement.runtimeStyle)
    {
      event.srcElement.runtimeStyle.backgroundColor = '';
      if (event.srcElement.attributes["oldbgcolor"])
        event.srcElement.runtimeStyle.backgroundColor = event.srcElement.attributes["oldbgcolor"].value;
      if (event.srcElement.attributes["oldborder"])
        event.srcElement.runtimeStyle.border = event.srcElement.attributes["oldborder"].value;        
      if (event.srcElement.attributes["oldclick"])
        event.srcElement.href = event.srcElement.attributes["oldclick"].value;
        
      event.srcElement.runtimeStyle.cursor = "";
      
      if (___markDiv)
      {
        ___markDiv.style.top = 0;
        ___markDiv.style.left = 0;
        ___markDiv.style.width = 0;
        ___markDiv.style.height = 0;
        ___markInnerDiv.style.top = 0;
        ___markInnerDiv.style.left = 0;
        ___markInnerDiv.style.width = 0;
        ___markInnerDiv.style.height = 0;
      }
      
   }
}


function Modify()
{
    var el = event.srcElement;
    
    var oldclick = document.createAttribute("oldclick");
    if (el.tagName == 'A')
    {
        if (!el.attributes["oldclick"])
        {
            oldclick.value = el.href;
            el.href = 'javascript:void(0)';
            el.attributes.setNamedItem(oldclick);
        }
    } 
    el.attachEvent('onclick',showMenu);    
    el.attachEvent('onmousedown',showMenu);  
    
    return;
}

function CRule(tag,classname,id)
{
	this.Tag = tag;
	this.CssClass = classname;
	this.ID = id;
	this.IsMatchID=function(xnode){		
		if (this.ID!="") //only check id
		{
			if (xnode.id==this.ID)
				return true;			
		}
		return false;
	}
	this.IsMatchTagClass=function(xnode){		
		if (this.Tag!="") //both classname and tag must match
		{
			if ((this.Tag==xnode.tagName) && (this.CssClass==xnode.className))
				return true;			
		}
		return false;
	}
	this.IsMatchClass=function(xnode){		
		if (this.CssClass!="")
		{
			if (xnode.className==this.CssClass)
				return true;
		}
		return false;
	}
	this.ToString=function()
	{
		if (this.ID!='')
			return '#'+this.ID;
		if (this.Tag=='')
			return '.'+this.CssClass;
		if ((this.Tag!='') && (this.CssClass!=''))
			return this.Tag + '.' + this.CssClass;
		if (this.Tag!='')
			return this.Tag;
		return '.'+this.CssClass;
		return this.ID+":"+this.CssClass+":"+this.Tag;
	}
}

function myrule(sn,sv)
{
	this.name=sn;
	this.value = sv;
}


function dm(msg)
{
    var debugWin = document.getElementById('___debugwin');
    if (!debugWin)
    {
        debugWin = document.createElement('div');
        debugWin.setAttribute('id','___debugwin');
        debugWin.style.position = 'absolute';
        debugWin.style.border = 'solid 1px yellow';
        debugWin.style.top = '5px';
        debugWin.style.left = '5px';
        
        document.body.appendChild(debugWin);
    }
    debugWin.innerHTML = msg;
}
/**********************************************
**      Ajax functions                       **
***********************************************/

var postInUse = false;
var postReq;
function PostCss(url,params)
{
	if (postInUse)
	{
		window.setTimeout('PostCss(\''+url+'\',\''+params+'\')',1000);
		return;
	}
	
	postInUse = true;
	
	if (window.XMLHttpRequest)
	{
		postReq = new XMLHttpRequest();
		postReq.onreadystatechange = processPostReqChange;
		postReq.open("POST",_appRoot + url,true);
        postReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        postReq.setRequestHeader("Content-length", params.length);
        postReq.setRequestHeader("Connection", "close");
		
		postReq.send(params);
		
	} else if (window.ActiveXObject)
	{
		postReq = new ActiveXObject("Microsoft.XMLHttp");
		if (postReq)
		{
			postReq.onreadystatechange = processPostReqChange;
			postReq.open("POST",_appRoot+url,true);
            postReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            postReq.setRequestHeader("Content-length", params.length);
            postReq.setRequestHeader("Connection", "close");
			postReq.send(params);
		}
	}
}

function processPostReqChange()
{
	if (postReq.readyState == 4)
	{
		if (postReq.status==200)
		{			
			//var response = req.responseXML.documentElement;			
			//var method = response.getElementsByTagName('method')[0].firstChild.data;						
			//var result = response.getElementsByTagName('data')[0];									
			savecssdone();
			
		}
		postInUse = false;
	}
}



/**********************************************
*       dragble window copied code            *
*       should be convert to ajax.net         *
***********************************************/
function hookEvent(element, eventName, callback)
{
  if(typeof(element) == "string")
    element = document.getElementById(element);
  if(element == null)
    return;
  if(element.addEventListener)
  {
    element.addEventListener(eventName, callback, false);
  }
  else if(element.attachEvent)
    element.attachEvent("on" + eventName, callback);
}

function unhookEvent(element, eventName, callback)
{
  if(typeof(element) == "string")
    element = document.getElementById(element);
  if(element == null)
    return;
  if(element.removeEventListener)
    element.removeEventListener(eventName, callback, false);
  else if(element.detachEvent)
    element.detachEvent("on" + eventName, callback);
}

function cancelEvent(e)
{
  e = e ? e : window.event;
  if(e.stopPropagation)
    e.stopPropagation();
  if(e.preventDefault)
    e.preventDefault();
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  return false;
}

function Position(x, y)
{
  this.X = x;
  this.Y = y;
  
  this.Add = function(val)
  {
    var newPos = new Position(this.X, this.Y);
    if(val != null)
    {
      if(!isNaN(val.X))
        newPos.X += val.X;
      if(!isNaN(val.Y))
        newPos.Y += val.Y
    }
    return newPos;
  }
  
  this.Subtract = function(val)
  {
    var newPos = new Position(this.X, this.Y);
    if(val != null)
    {
      if(!isNaN(val.X))
        newPos.X -= val.X;
      if(!isNaN(val.Y))
        newPos.Y -= val.Y
    }
    return newPos;
  }
  
  this.Min = function(val)
  {
    var newPos = new Position(this.X, this.Y)
    if(val == null)
      return newPos;
    
    if(!isNaN(val.X) && this.X> val.X)
      newPos.X = val.X;
    if(!isNaN(val.Y) && this.Y> val.Y)
      newPos.Y = val.Y;
    
    return newPos;  
  }
  
  this.Max = function(val)
  {
    var newPos = new Position(this.X, this.Y)
    if(val == null)
      return newPos;
    
    if(!isNaN(val.X) && this.X <val.X)
      newPos.X = val.X;
    if(!isNaN(val.Y) && this.Y <val.Y)
      newPos.Y = val.Y;
    
    return newPos;  
  }  
  
  this.Bound = function(lower, upper)
  {
    var newPos = this.Max(lower);
    return newPos.Min(upper);
  }
  
  this.Check = function()
  {
    var newPos = new Position(this.X, this.Y);
    if(isNaN(newPos.X))
      newPos.X = 0;
    if(isNaN(newPos.Y))
      newPos.Y = 0;
    return newPos;
  }
  
  this.Apply = function(element)
  {
    if(typeof(element) == "string")
      element = document.getElementById(element);
    if(element == null)
      return;
    if(!isNaN(this.X))
      element.style.left = this.X + 'px';
    if(!isNaN(this.Y))
      element.style.top = this.Y + 'px';  
  }
}

function absoluteCursorPostion(eventObj)
{
  eventObj = eventObj ? eventObj : window.event;
  
  if(isNaN(window.scrollX))
    return new Position(eventObj.clientX + 
              document.documentElement.scrollLeft + 
              document.body.scrollLeft, 
              eventObj.clientY + 
              document.documentElement.scrollTop + 
              document.body.scrollTop);
  else
    return new Position(eventObj.clientX + window.scrollX, 
              eventObj.clientY + window.scrollY);
}

function dragObject(element, attachElement, 
    lowerBound, upperBound, startCallback, 
    moveCallback, endCallback, attachLater)
{
  if(typeof(element) == "string")
    element = document.getElementById(element);
  if(element == null)
      return;
  
  if(lowerBound != null && upperBound != null)
  {
    var temp = lowerBound.Min(upperBound);
    upperBound = lowerBound.Max(upperBound);
    lowerBound = temp;
  }

  var cursorStartPos = null;
  var elementStartPos = null;
  var dragging = false;
  var listening = false;
  var disposed = false;
  
  function dragStart(eventObj)
  { 
    if(dragging || !listening || disposed) return;
    dragging = true;
    
    if(startCallback != null)
      startCallback(eventObj, element);
    
    cursorStartPos = absoluteCursorPostion(eventObj);
    
    elementStartPos = new Position(parseInt(element.style.left),
        parseInt(element.style.top));
   
    elementStartPos = elementStartPos.Check();
    
    hookEvent(document, "mousemove", dragGo);
    hookEvent(document, "mouseup", dragStopHook);
    
    return cancelEvent(eventObj);
  }
  
  function dragGo(eventObj)
  {
    if(!dragging || disposed) return;
    
    var newPos = absoluteCursorPostion(eventObj);
    newPos = newPos.Add(elementStartPos).Subtract(cursorStartPos);
    newPos = newPos.Bound(lowerBound, upperBound)
    newPos.Apply(element);
    if(moveCallback != null)
      moveCallback(newPos, element);
        
    return cancelEvent(eventObj); 
  }
  
  function dragStopHook(eventObj)
  {
    dragStop();
    return cancelEvent(eventObj);
  }
  
  function dragStop()
  {
    if(!dragging || disposed) return;
    unhookEvent(document, "mousemove", dragGo);
    unhookEvent(document, "mouseup", dragStopHook);
    cursorStartPos = null;
    elementStartPos = null;
    if(endCallback != null)
      endCallback(element);
    dragging = false;
  }
  
  this.Dispose = function()
  {
    if(disposed) return;
    this.StopListening(true);
    element = null;
    attachElement = null
    lowerBound = null;
    upperBound = null;
    startCallback = null;
    moveCallback = null
    endCallback = null;
    disposed = true;
  }
  
  this.StartListening = function()
  {
    if(listening || disposed) return;
    listening = true;
    hookEvent(attachElement, "mousedown", dragStart);
  }
  
  this.StopListening = function(stopCurrentDragging)
  {
    if(!listening || disposed) return;
    unhookEvent(attachElement, "mousedown", dragStart);
    listening = false;
    
    if(stopCurrentDragging && dragging)
      dragStop();
  }
  
  this.IsDragging = function(){ return dragging; }
  this.IsListening = function() { return listening; }
  this.IsDisposed = function() { return disposed; }
  
  if(typeof(attachElement) == "string")
    attachElement = document.getElementById(attachElement);
  if(attachElement == null)
    attachElement = element;
    
  if(!attachLater)
    this.StartListening();
}
